<template>
	<view class="album-detail">
		<u-navbar title="专辑详情" :safeAreaInsetTop="true" fixed placeholder>
			<view class="u-nav-slot" slot="left">
				<u-icon name="arrow-left" size="19" @click="goBack"></u-icon>
				<u-line direction="column" :hairline="false" length="16" margin="0 8px"></u-line>
				<u-icon name="home" size="20" @click="goHome"></u-icon>
			</view>
		</u-navbar>
		<!-- 专辑封面信息区 -->
		<view class="album-header">
			<view class="image-wrapper">
				<image :src="albumInfo.coverUrl" mode="aspectFit" />
				<view class="album_view overlay">
					<u-icon name="play-right" size="12" color="#fff"></u-icon>
					<text>{{ formatViewCount(albumInfo.viewCount) }}</text>
				</view>
			</view>
			<view class="album-info">
				<text class="album-title">{{ albumInfo.title }}</text>
				<view class="author-info">
					<text>{{ albumInfo.author }}</text>
				</view>
				<view class="author-info">
					<view class="tag" v-for="(tag, index) in albumInfo.tags" :key="index">{{ tag }}</view>
					<view class="star">
						<u-icon name="star-fill" size="12" color="#bc8f1e" v-for="(star, index) in albumInfo.star" :key="index"></u-icon>
						<text>{{ albumInfo.star }}</text>
					</view>
				</view>
				<view class="action">
					<view class="action-item" @click="handleCollect">
						<u-icon :name="albumInfo.iscollect ? 'heart-fill' : 'heart'" size="20" :color="albumInfo.iscollect ? '#f56c6c' : ''"></u-icon>
						<text>收藏</text>
					</view>
					<button class="u-reset-button action-item wechat" open-type="share">
						<u-icon name="weixin-fill" size="24" color="#fff"></u-icon>
						<text>分享</text>
					</button>
				</view>
			</view>
		</view>

		<u-sticky bgColor="#fff" :customNavHeight="customNavHeight">
			<u-tabs
				:list="tabs"
				@change="handleTabChange"
				:scrollable="false"
				lineWidth="30"
				lineColor="#f56c6c"
				:activeStyle="{
					color: '#303133',
					fontWeight: 'bold',
					transform: 'scale(1.1)'
				}"
				:inactiveStyle="{
					color: '#606266',
					transform: 'scale(1)'
				}"
				itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;"
			></u-tabs>
		</u-sticky>

		<block v-if="activeTab === 0">
			<!-- 播放全部区域 -->
			<view class="play-all">
				<view class="left" @click="goPlayAll">
					<u-icon name="play-circle" size="20" />
					<text>播放全部</text>
					<text class="episode-count">(共{{ episodeList.length }}集)</text>
				</view>
				<view class="right" v-if="orederBy == 'asc'" @click="handleOrderBy()">
					<image src="../../static/img/order_acs.svg" mode="widthFix"></image>
					<text>排序</text>
				</view>
				<view class="right" v-else @click="handleOrderBy()">
					<image src="../../static/img/order_decs.svg" mode="widthFix"></image>
					<text>排序</text>
				</view>
			</view>

			<!-- 节目列表 -->
			<!-- <scroll-view
				class="episode-list"
				scroll-y
				@scrolltolower="loadMore"
				@refresherrefresh="onRefresh"
				refresher-enabled
				:refresher-triggered="isRefreshing"
			> -->
			<scroll-view class="episode-list" scroll-y>
				<view class="episode-item" v-for="(item, index) in episodeList" :key="index" @click="goPlay(item)">
					<view class="episode-info">
						<text class="episode-index">{{ index + 1 }}</text>
						<view class="episode-main">
							<view class="episode-title">
								{{ item.title }}
							</view>
							<view class="episode-stats">
								<view class="episode-stats-item">
									<u-icon name="file-text" size="14" color="#999" />
									<text>{{ item.size }}</text>
								</view>
								<view class="episode-stats-item">
									<u-icon name="clock" size="14" color="#999" />
									<text>{{ formatTime(item.duration) }}</text>
								</view>
								<!-- <view class="episode-stats-item">
									<u-icon name="server-fill" size="12" color="#999" />
									<text>{{ item.playCount }}</text>
								</view> -->
								<!-- <view class="episode-stats-item">
									<u-icon name="clock" size="12" color="#999" />
									<text>{{ item.duration }}</text>
								</view> -->
							</view>
						</view>
					</view>
					<view>
						<u-icon name="play-circle" size="30" color="#999" />
					</view>
				</view>

				<!-- Loading state -->
				<view class="loading-more" v-if="isLoadingMore">
					<u-loading-icon></u-loading-icon>
					<text>加载中...</text>
				</view>
			</scroll-view>
		</block>
		<block v-else-if="activeTab === 1">
			<view class="intro">
				<text>{{ albumInfo.description }}</text>
			</view>
		</block>
		<block v-else-if="activeTab === 2">
			<view class="comment-list">
				<view class="comment-item" v-for="(item, index) in commentList" :key="index">
					<view class="comment-header">
						<image :src="item.user.avatar" mode="aspectFill" />
					</view>
					<view class="comment-content">
						<view class="nickname">{{ item.user.nickname }}</view>
						<view class="star">
							<u-icon name="star-fill" size="12" color="#F3DF50" v-for="i in item.star" :key="i"></u-icon>
						</view>
						<view class="content">{{ item.content }}</view>
						<view class="create-time">{{ item.createTime }}</view>
					</view>
				</view>
			</view>
		</block>
		<view class="audioPlayer"><audioPlayerVue /></view>
	</view>
</template>

<script>
import { formatViewCount } from '../../utils/format.js';
import { episodeList, albumInfo, commentList } from '../../mock/home.js';
import globalAudioplayerVue from '../../components/global-audioplayer.vue';
import audioPlayerVue from '@/components/audio-player.vue';
export default {
	components: {
		globalAudioplayerVue,
		audioPlayerVue
	},
	data() {
		return {
			tabs: [
				{
					name: '节目',
					index: 0
				},
				{
					name: '简介',
					index: 1
				}
				// {
				// 	name: '评价',
				// 	index: 2
				// }
			],
			activeTab: 0,
			customNavHeight: 0,
			episodeList: [],
			albumInfo: {},
			commentList,
			isRefreshing: false,
			isLoadingMore: false,
			page: 1,
			hasMore: true,
			orederBy: 'asc',
			shareInfo: {
				title: '',
				path: ''
			},
			AccountInfo: {}
		};
	},
	onLoad(option) {
		this.albumInfo.id = option.id;
		// Get custom navbar height
		// const systemInfo = uni.getSystemInfoSync();
		const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
		this.customNavHeight = menuButtonInfo.bottom;
		this.getInfo();
		let AccountInfo = wx.getAccountInfoSync();
		if (AccountInfo.miniProgram.envVersion !== 'release') {
			this.tabs = [
				{
					name: '简介',
					index: 1
				}
			];
			this.activeTab = 1;
		}
	},
	// 这里如果写成onShareAppMessage: res => { ... }形式的箭头函数，在内部会无法获得this
	onShareAppMessage(res) {
		if (res.from === 'button') {
			// 来自页面内分享按钮
			console.log(res.target);
		}
		return this.shareInfo;
	},
	methods: {
		formatViewCount,
		getInfo() {
			let PostData = {
				ac: 'getdetail',
				id: this.albumInfo.id
			};
			let that = this;
			uni.$u.http.post('', PostData).then((res) => {
				console.log(res);
				let albumInfo = {
					id: res.id,
					coverUrl: res.data.cover_url,
					title: res.data.title.split(' by ')[0].trim(),
					tags: res.data.tags,
					star: res.data.star,
					author: res.data.author,
					description: res.data.description,
					viewCount: res.data.views,
					iscollect: res.iscollect
				};
				this.albumInfo = albumInfo;
				this.shareInfo.title = albumInfo.title;
				this.shareInfo.path = `pages/album/detail?id=${albumInfo.id}`;
				let episodeList = res.list.map((item) => {
					return {
						id: item.id,
						title: item.title,
						size: item.real_size + 'MB',
						part: item.part,
						books_id: item.books_id,
						duration: item.duration,
						singer: item.singer
						// playCount: ,
						// duration:
					};
				});
				this.episodeList = episodeList;
			});
		},
		handleTabChange(item) {
			this.activeTab = item.index;
		},
		handleCollect() {
			uni.showLoading();
			if (!this.albumInfo.iscollect) {
				let PostData = {
					ac: 'addcollect',
					id: this.albumInfo.id
				};
				uni.$u.http.post('', PostData).then((res) => {
					uni.showToast({
						title: '收藏成功',
						icon: 'none'
					});
				});
			} else {
				let PostData = {
					ac: 'delcollect',
					id: this.albumInfo.id
				};
				uni.$u.http.post('', PostData).then((res) => {
					uni.showToast({
						title: '取消收藏',
						icon: 'none'
					});
				});
			}

			this.albumInfo.iscollect = !this.albumInfo.iscollect;
		},
		handleOrderBy() {
			if (this.orederBy == 'asc') {
				this.orederBy = 'decs';
			} else {
				this.orederBy = 'asc';
			}
			this.episodeList.reverse();
		},
		goBack() {
			uni.navigateBack();
		},
		goHome() {
			uni.switchTab({ url: '/pages/index/index' });
		},
		goPlayAll() {
			let PostData = {
				ac: 'addbooktoplaylist',
				books_id: this.albumInfo.id
			};
			uni.$u.http.post('', PostData).then((res) => {
				uni.navigateTo({ url: '/pages/album/play' });
			});
		},
		goPlay(item) {
			let PostData = {
				ac: 'addplaylist',
				books_id: item.books_id,
				mp3file_id: item.id,
				part: item.part
			};
			uni.$u.http.post('', PostData).then((res) => {
				uni.navigateTo({ url: `/pages/album/play?mp3file_id=${item.id}` });
			});
		},
		async onRefresh() {
			this.isRefreshing = true;
			try {
				this.page = 1;
				// Replace with your actual API call
				const newData = await this.fetchEpisodeList(1);
				this.episodeList = newData;
			} catch (error) {
				console.error('Refresh failed:', error);
			} finally {
				this.isRefreshing = false;
			}
		},
		async loadMore() {
			if (this.isLoadingMore || !this.hasMore) return;

			this.isLoadingMore = true;
			try {
				// Replace with your actual API call
				const moreData = await this.fetchEpisodeList(this.page + 1);
				if (moreData.length) {
					this.episodeList = [...this.episodeList, ...moreData];
					this.page++;
				} else {
					this.hasMore = false;
				}
			} catch (error) {
				console.error('Load more failed:', error);
			} finally {
				this.isLoadingMore = false;
			}
		},
		async fetchEpisodeList(page) {
			// Replace this with your actual API call
			return new Promise((resolve) => {
				setTimeout(() => {
					const totalEpisodes = 100;
					const pageSize = 20;

					if (page * pageSize > totalEpisodes) {
						resolve();
						return;
					}

					const episodes = this.generateMockEpisodes((page - 1) * pageSize + 1, pageSize);
					console.log('episodes', episodes);
					resolve(episodes);
				}, 1000);
			});
		},
		//模拟加载数据
		generateMockEpisodes(startIndex, count) {
			return Array.from({ length: count }, (_, index) => ({
				id: startIndex + index,
				title: `西游记 第${startIndex + index}集 ${['开篇', '初相遇', '转折点', '高潮', '尾声'][Math.floor(Math.random() * 5)]}`,
				playCount: `${Math.floor(Math.random() * 10 + 1)}.${Math.floor(Math.random() * 9)}万`,
				duration: `${Math.floor(Math.random() * 30 + 20)}:${Math.floor(Math.random() * 59)
					.toString()
					.padStart(2, '0')}`
			}));
		},

		formatFileSize(bytes) {
			if (bytes === 0) return '0 Bytes';

			const k = 1024;
			const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
			const i = Math.floor(Math.log(bytes) / Math.log(k));

			return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
		},
		//时间格式化
		formatTime(seconds) {
			const min = Math.floor(seconds / 60);
			const sec = Math.floor(seconds % 60);
			return `${min < 10 ? '0' + min : min}:${sec < 10 ? '0' + sec : sec}`;
		}
	}
};
</script>

<style lang="scss" scoped>
.audioPlayer {
	position: fixed;
	bottom: calc(env(safe-area-inset-bottom));
	height: 100rpx;
	left: 50%;
	transform: translateX(-50%);
}
.u-nav-slot {
	display: flex;
	align-items: center;
}
.album-detail {
	//   background-color: #f5f5f5;
	min-height: 100vh;

	.album-header {
		padding: 20rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		.image-wrapper {
			position: relative;
			width: 240rpx;
			display: block;
			font-size: 0;

			image {
				width: 100%;
				height: 240rpx;
				border-radius: 8rpx;
				display: block;
			}

			.album_view.overlay {
				box-sizing: border-box;
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				background: linear-gradient(to top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));
				color: #fff;
				padding: 8rpx;
				font-size: 20rpx;
				display: flex;
				align-items: center;
				justify-content: flex-start;
				gap: 10rpx;
				border-radius: 0 0 8rpx 8rpx;
				white-space: nowrap;
				overflow: hidden;
				height: 60rpx;
			}
		}

		.album-info {
			flex: 1;
			margin-left: 20rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			.album-title {
				font-size: 36rpx;
				font-weight: bold;
			}

			.author-info {
				display: flex;
				align-items: center;
				margin: 10rpx 0;
				font-size: 24rpx;
				gap: 10rpx;
				.tag {
					background-color: #ddae9f;
					color: #bc8f1e;
					padding: 5rpx 10rpx;
					border-radius: 10rpx;
				}

				.star {
					background-color: #ddae9f;
					color: #bc8f1e;
					padding: 5rpx 10rpx;
					border-radius: 10rpx;
					display: flex;
					align-items: center;
				}
			}

			.action {
				display: flex;
				align-items: center;
				margin-top: 10rpx;
				gap: 20rpx;
				.action-item {
					display: flex;
					align-items: center;
					margin-right: 20rpx;
					color: #999;
					font-size: 28rpx;
					border: 1rpx solid #999;
					padding: 5rpx 20rpx;
					border-radius: 50rpx;
					gap: 10rpx;
				}
				.wechat {
					background-color: #00bb00;
					color: #fff;
					border: none;
				}
			}
		}
	}

	.tabs {
		border-bottom: 1rpx solid #eee;
	}

	.play-all {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 40rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
		// margin-top: 20rpx;

		.left {
			display: flex;
			align-items: center;
			gap: 10rpx;
			.episode-count {
				color: #999;
				margin-left: 10rpx;
			}
		}

		.right {
			display: flex;
			align-items: center;
			gap: 10rpx;
			image {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}

	.episode-list {
		height: calc(100vh - 400rpx);
		padding-bottom: 40rpx;
		.episode-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 40rpx;
			background-color: #fff;
			border-bottom: 1rpx solid #eee;

			.episode-info {
				flex: 1;
				display: flex;
				align-items: center;
				gap: 20rpx;

				.episode-index {
					color: #999;
					font-size: 28rpx;
					min-width: 40rpx;
				}

				.episode-main {
					flex: 1;
					.episode-title {
						font-size: 28rpx;
						margin-bottom: 10rpx;
					}

					.episode-stats {
						display: flex;
						align-items: center;
						gap: 20rpx;

						.episode-stats-item {
							display: flex;
							align-items: center;
							gap: 10rpx;
							color: #999;
							font-size: 24rpx;
						}
					}
				}
			}
		}

		.loading-more {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 20rpx;
			color: #999;
			font-size: 24rpx;

			text {
				margin-left: 10rpx;
			}
		}
	}

	.intro {
		padding: 20rpx 40rpx;
		background-color: #fff;
		font-size: 28rpx;
		color: #999;
		padding-bottom: 100rpx;
	}

	.comment-list {
		padding: 20rpx 40rpx;
		background-color: #fff;
		.comment-item {
			display: flex;
			align-items: flex-start;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #eee;
			.comment-header {
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
				overflow: hidden;
				image {
					width: 100%;
					height: 100%;
				}
			}

			.comment-content {
				flex: 1;
				margin-left: 20rpx;
				display: flex;
				flex-direction: column;
				gap: 10rpx;
				.nickname {
					font-size: 28rpx;
					font-weight: bold;
				}
				.star {
					display: flex;
					align-items: center;
					gap: 10rpx;
				}
				.content {
					font-size: 24rpx;
					color: #999;
				}
				.create-time {
					font-size: 24rpx;
					color: #999;
					margin-top: 10rpx;
				}
			}
		}
	}
}
</style>